class Cache {
    constructor() {
        this.cache = new Map();
        this.defaultTTL = 3600; // 默认缓存时间1小时（秒）
    }

    set(key, value, ttl = this.defaultTTL) {
        const expiresAt = Date.now() + (ttl * 1000);
        this.cache.set(key, {
            value,
            expiresAt
        });
    }

    get(key) {
        const data = this.cache.get(key);
        if (!data) return null;

        if (Date.now() > data.expiresAt) {
            this.cache.delete(key);
            return null;
        }

        return data.value;
    }

    delete(key) {
        return this.cache.delete(key);
    }

    clear() {
        this.cache.clear();
    }

    // 为特定用户缓存数据
    setUserData(userId, key, value, ttl = this.defaultTTL) {
        const userKey = `user:${userId}:${key}`;
        this.set(userKey, value, ttl);
    }

    // 获取特定用户的缓存数据
    getUserData(userId, key) {
        const userKey = `user:${userId}:${key}`;
        return this.get(userKey);
    }

    // 缓存任务数据
    setTaskData(taskId, data, ttl = this.defaultTTL) {
        const taskKey = `task:${taskId}`;
        this.set(taskKey, data, ttl);
    }

    // 获取任务缓存数据
    getTaskData(taskId) {
        const taskKey = `task:${taskId}`;
        return this.get(taskKey);
    }

    // 缓存宠物数据
    setPetData(petId, data, ttl = this.defaultTTL) {
        const petKey = `pet:${petId}`;
        this.set(petKey, data, ttl);
    }

    // 获取宠物缓存数据
    getPetData(petId) {
        const petKey = `pet:${petId}`;
        return this.get(petKey);
    }

    // 清理过期缓存
    cleanup() {
        const now = Date.now();
        for (const [key, data] of this.cache.entries()) {
            if (now > data.expiresAt) {
                this.cache.delete(key);
            }
        }
    }
}

// 创建一个全局缓存实例
const cache = new Cache();

// 定期清理过期缓存（每小时）
setInterval(() => {
    cache.cleanup();
}, 3600 * 1000);

module.exports = cache;